//
//  ForgetViewController.m
//  TodatPlay
//
//  Created by dllo on 16/9/17.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "ForgetViewController.h"
#import "AFNetworking.h"
#import "CDMNetTool.h"
@interface ForgetViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UITextField *inputPassWord;
@property (weak, nonatomic) IBOutlet UITextField *makeSurePassWord;
@property (weak, nonatomic) IBOutlet UIButton *getCode;

@end

@implementation ForgetViewController {
    int secondsCountDown; //倒计时总时长
    NSTimer *countDownTimer;
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    // 使状态栏颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    // 是的状态栏颜色为黑色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"忘记密码";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icons_back_dark"] style:UIBarButtonItemStylePlain target:self action:@selector(handleLeft:)];
    
    self.getCode.layer.cornerRadius = self.getCode.frame.size.height / 2.0;
    self.getCode.layer.borderWidth = 1;
    self.getCode.layer.borderColor = [UIColor blackColor].CGColor;
    
    self.phoneNumber.delegate = self;
    self.makeSurePassWord.delegate = self;
    
    self.phoneNumber.keyboardType = UIKeyboardTypePhonePad;
    self.codeTextField.keyboardType = UIKeyboardTypePhonePad;
    self.inputPassWord.secureTextEntry = YES;
    self.makeSurePassWord.secureTextEntry = YES;
    
    
}
- (void)handleLeft:(UIBarButtonItem *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - textfieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.makeSurePassWord.text != self.inputPassWord.text) {
        NSLog(@"两次密码输入不一样");
    }
    if ([self valiMobile:self.phoneNumber.text]) {
        NSLog(@"这个是电话号");
    } else {
        NSLog(@"这个不是电话号");
    }
    
    if (self.inputPassWord.text.length < 6 || self.inputPassWord.text.length > 16) {
        self.makeSurePassWord.placeholder = @"密码长度不正确";
    }
    
}
// 通过正则表达式判断电话输入框中的内容是否是电话号
- (BOOL)valiMobile:(NSString *)mobile{
    
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}


- (IBAction)getCode:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://wanapi.damai.cn/mapi/user/findpassword.json";
    NSString *parameters = @"platform=4&channel_from=m360_market&source=10345&version=203004";
    //
    NSString *newParmeter = [parameters stringByAppendingFormat:@"&account=%@", self.phoneNumber.text];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 3. 设置请求参数的字符串格式, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [set addObject:@"text/html"];
    [manager.responseSerializer setAcceptableContentTypes:set];
    
    [manager GET:postURLString parameters:newParmeter progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发送验证码请求成功: %@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"发送验证码请求失败: %@", error);
    }];
    
    // 倒计时
    //设置倒计时总时长
    secondsCountDown = 60;//60秒倒计时
    //开始倒计时
    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
    //设置倒计时显示的时间
    NSString *timeStr = [NSString stringWithFormat:@"%ds",secondsCountDown]; ;
    [self.getCode setTitle:timeStr forState:UIControlStateNormal];
    [self.getCode removeTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];

}
#pragma mark - 实现倒计时方法
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    NSString *timeStr = [NSString stringWithFormat:@"%ds",secondsCountDown]; ;
    [self.getCode setTitle:timeStr forState:UIControlStateNormal];
    
    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        [self.getCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.getCode addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    }
}


- (IBAction)complete:(id)sender {
    NSString *changePassWord = @"http://wanapi.damai.cn/mapi/user/ReSetPass.json?platform=4&source=10345&version=203004&useCash=false&channel_from=m360_market";
    NSString *phoneNumber = self.phoneNumber.text;
    NSString *code = self.codeTextField.text;
    NSString *passWord = self.makeSurePassWord.text;
    NSString *finalString = [[[changePassWord stringByAppendingFormat:@"&name=%@", phoneNumber]stringByAppendingFormat:@"&code=%@", code]stringByAppendingFormat:@"&password=%@", passWord];
    [CDMNetTool GET:finalString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        NSLog(@"修改密码请求成功%@", result);
        // 当修改密码成功后返回到登录界面
        [self.navigationController popViewControllerAnimated:YES];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"修改密码请求失败%@", error);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
